import { Body, Controller, Delete, Get, HttpException, HttpStatus, Param, Patch, Post, Query } from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
import { EEnableStatus } from '@/shared/types/globalEnum'
import { DownloadService } from './download.service'
import { CreateDownloadDto, ListPageDownloadDto, UpdateDownloadDto } from './dto/download.dto'

@ApiTags('后台/下载配置')
@Controller('admin/download')
export class DownloadController {
  constructor(private readonly downloadService: DownloadService) {}

  /**
   * 下载配置列表
   */
  @Get()
  list(
    @Query()
    query: ListPageDownloadDto,
  ) {
    return this.downloadService.findPage(query)
  }

  /**
   * 下载配置详情
   */
  @Get(':downloadId')
  detail(
    @Param('downloadId')
    downloadId: number,
  ) {
    return this.downloadService.findOne({
      downloadId,
    })
  }

  /**
   * 创建下载配置
   */
  @Post()
  async create(@Body() data: CreateDownloadDto) {
    if (data.useStatus === EEnableStatus.ENABLED) {
      await this.downloadService.setAllDisable()
    }
    return this.downloadService.create(data)
  }

  /**
   * 更新下载配置
   */
  @Patch(':downloadId')
  async update(
    @Param('downloadId')
    downloadId: number,
    @Body()
    data: UpdateDownloadDto,
  ) {
    const findData = await this.downloadService.findOne({
      downloadId,
    })
    if (!findData) {
      throw new HttpException('下载配置不存在', HttpStatus.NOT_FOUND)
    }
    if (data.useStatus === EEnableStatus.ENABLED) {
      await this.downloadService.setAllDisable()
    }
    await this.downloadService.update(downloadId, data)
  }

  /**
   * 删除下载配置
   */
  @Delete(':downloadId')
  async remove(@Param('downloadId') downloadId: number) {
    const findData = await this.downloadService.findOne({
      downloadId,
    })
    if (!findData) {
      throw new HttpException('下载配置不存在', HttpStatus.NOT_FOUND)
    }
    await this.downloadService.remove(downloadId)
  }
}

@ApiTags('官网/下载配置')
@Controller('web/download')
export class WebDownloadController {
  constructor(private readonly downloadService: DownloadService) {}
  /**
   * 当前使用的下载配置
   */
  @Get()
  webDetail() {
    return this.downloadService.findOne({
      useStatus: EEnableStatus.ENABLED,
    })
  }
}
